package com.ai.imagetext.config;

import cn.hutool.core.io.FileUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.VoidResult;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@Component
@Data
@ConfigurationProperties(prefix = "oss")
public class AliOSSManager {

    private String endpoint;

    private String accessKeyId;

    private String accessKeySecret;

    private String bucketName;

    private String folderName;

    /**
     * 实现上传图片到OSS
     */
    public String upload(MultipartFile multipartFile,String relativePath) throws IOException {
        // 文件校验
        long size = multipartFile.getSize();
        if (size > 5 * 1024 * 1024L) {
            throw new RuntimeException("文件大小不能超过10M");
        }
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        final List<String> validFileSuffixList = Arrays.asList("jpg", "png", "jpeg", "gif", "bmp","webp","avif");
        if (!validFileSuffixList.contains(fileSuffix)) {
            throw new RuntimeException("文件格式不支持");
        }

        // 获取上传的文件的输入流
        InputStream inputStream = multipartFile.getInputStream();

        String fileName = folderName + relativePath;

        //上传文件到 OSS
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.putObject(bucketName, fileName, inputStream);

        String url = "https://" + bucketName + "." + endpoint + "/" + fileName;

        System.out.println("-----------------------------------------");
        System.out.println("上传成功，文件路径为：" + url);
        System.out.println("-----------------------------------------");

        // 关闭ossClient
        ossClient.shutdown();
        return url;// 把上传到oss的路径返回
    }

    /**
     * 删除OSS上的图片
     */
    public void delete(String relativePath) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        VoidResult voidResult = ossClient.deleteObject(bucketName, relativePath);
        ossClient.shutdown();
    }

    /**
     * 查询OSS上的文件是否存在
     */
    public boolean exists(String relativePath) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        boolean result = ossClient.doesObjectExist(bucketName, relativePath);
        ossClient.shutdown();
        return result;
    }
}
